package com.lemon.core.sms.service;

import cn.hutool.json.JSONUtil;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.lemon.core.base.util.StringPool;
import com.lemon.core.sms.config.AliyunSmsProperties;
import com.lemon.core.sms.domain.SmsResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 阿里云短信服务
 *
 * @author pan
 * @since 2017-09-06
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AliyunSmsSendService implements SmsSendService {

    private static final String SUCCESS_CODE = "OK";
    private final AliyunSmsProperties aliyunSmsProperties;

    /**
     * 获取默认客户端
     *
     * @return
     */
    public IAcsClient getDefaultAcsClient() {
        DefaultProfile profile = DefaultProfile.getProfile(aliyunSmsProperties.getRegionId(), aliyunSmsProperties.getAccessKey(), aliyunSmsProperties.getKeySecret());
        DefaultProfile.addEndpoint(aliyunSmsProperties.getRegionId(), aliyunSmsProperties.getProduct(), aliyunSmsProperties.getDomain());
        // 可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        return new DefaultAcsClient(profile);
    }

    @Override
    public SmsResponse sendSmsCode(String code, List<String> phoneNumbers) {
        SmsResponse smsResponse = new SmsResponse();
        SendSmsRequest request = new SendSmsRequest();
        request.setSysMethod(MethodType.POST);
        request.setPhoneNumbers(String.join(StringPool.COMMA, phoneNumbers));
        request.setSignName(aliyunSmsProperties.getSignName());
        request.setTemplateCode(aliyunSmsProperties.getTemplateCode());

        Map<String, Object> params = new HashMap<>();
        params.put("code", code);
        request.setTemplateParam(JSONUtil.toJsonStr(params));

        try {
            SendSmsResponse response = getDefaultAcsClient().getAcsResponse(request);
            if (SUCCESS_CODE.equals(response.getCode())) {
                smsResponse.setSuccess(true);
            }
            smsResponse.setCode(response.getCode());
            smsResponse.setMessage(response.getMessage());
        } catch (Exception e) {
            log.error("Send Aliyun Sms Fail: ", e);
            smsResponse.setMessage("Send Aliyun Sms Fail!");
        }
        return smsResponse;
    }

}
